package com.gameloft.futbol.element;

import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;
import com.gameloft.futbol.element.screen.MainScreen;
import com.gameloft.futbol.Element;
import com.gameloft.futbol.fCanvas;
import com.gameloft.futbol.fMidlet;
import com.gameloft.futbol.Util;
import com.gameloft.input.Pointer;
import com.gameloft.input.Keypad;


public class Button extends Element
{
	
	int id;
	String caption;
	Image[] anim;
	
	boolean selected;
	boolean highlighted;
	int frame;
	
	
	public Button(int id, String caption, String imgFilename)
	{
		this.id = id;
		this.caption = caption;
		Image icon = Util.loadImage(imgFilename);
		anim = new Image[6];
		int[] argb = Util.getImageRGB(icon);
		anim[0] = Util.resizeImage(argb, icon.getWidth(), icon.getHeight(), 30, 30);
		anim[1] = Util.resizeImage(argb, icon.getWidth(), icon.getHeight(), 40, 40);
		anim[2] = Util.resizeImage(argb, icon.getWidth(), icon.getHeight(), 50, 50);
		anim[3] = anim[2];
		anim[4] = anim[1];
		anim[5] = anim[0];
	}
	
	public int getId()
	{
		return id;
	}
	
	public String getCaption()
	{
		return caption;
	}
	
	public boolean isSelected()
	{
		return selected;
	}
	
	public boolean isHighlighted()
	{
		return highlighted;
	}
	
	public void update(long elapsed)
	{
		if (fCanvas.isTouchScreen())
		{
			setHighlighted(Pointer.isInRect(x, y, w, h));
			if (Pointer.releasedInRect(x, y, w, h)) ((MainScreen)parent).setCurrentMenu(id);
		}
		
		int prevFrame = frame;
		if (highlighted)
			frame = (frame < anim.length-1) ? (frame+1) : 0;
		else
			frame = 0;
		if (prevFrame != frame) invalidate();
	}
	
	public void paint(Graphics g, int rectX, int rectY, int rectW, int rectH)
	{
		Util.pushClip(g, x, y, w, h);
		
		//Draw button background
		for (int i = 0; i < h; i++)
		{
			int k = 0;
			if (i < h/2)
				k = 170 - (selected?70:0) - (2*i*100)/h;
			else
				k = 20 + ((2*i-h)*80)/h;
			int red = (k + (highlighted?40:0));
			int green = (k + (highlighted?40:0));
			int blue = (k + (highlighted?0:20));
			g.setColor((red << 16) | (green << 8) | (blue));
			g.drawLine(x, y+i, x+w, y+i);
		}
		g.setColor(0x808080);
		g.drawLine(x, y, x, y+h);
		g.setColor(0x202020);
		g.drawLine(x+w-1, y, x+w-1, y+h);
		
		//Draw button icon
		g.drawImage(anim[frame], x + (w>>1), y + (h>>1), Graphics.HCENTER | Graphics.VCENTER);
		
		Util.popClip(g);
	}
	
	public void setSelected(boolean selected)
	{
		if (this.selected != selected) invalidate();
		this.selected = selected;
	}
	
	public void setHighlighted(boolean highlighted)
	{
		if (this.highlighted != highlighted) invalidate();
		this.highlighted = highlighted;
	}
	
}